﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MedicalCare.Messages;
using StructureMap;
using MedicalCare.DbLayer.Adaptors;
using MedicalCare.EntityDefinitions.Entities;
using System.Web.Script.Serialization;

namespace MedicalCare.WebHandler
{
    /// <summary>
    /// 关于评论回复的获取和发表
    /// </summary>
    public class CommentReply : IHttpHandler
    {
        private IScheduleAdaptor scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();
        public void ProcessRequest(HttpContext context)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            IList<ScheduleCommentReplyEntity> finalResutCommentReply = null;
            string actionType = context.Request["action"].ToString();
            int commentId = int.Parse(context.Request["commentId"].ToString());
            string replyContent = context.Request["replyContent"];
            switch (actionType)
            {
                case "get": //获取评论列表
                    finalResutCommentReply = GetCommentReplys(commentId);
                    break;
                case "add": //添加评论列表
                    if (!string.IsNullOrEmpty(replyContent))
                    {
                        var scheduleCommentReplyMsg = new ScheduleCommentReplyMessage()
                        {
                            UserId = AppPage.CurrentUser.Id,
                            ReplyCommentId = commentId,
                            ReplyContent = replyContent
                        };
                        int result = scheduleAdaptor.AddCommentsReplys(scheduleCommentReplyMsg);
                        if (result != -1)//成功插入数据
                        {
                           finalResutCommentReply = GetCommentReplys(commentId);
                        }
                    }
                    break;
                default:
                    break;
            }

            string data = serializer.Serialize(finalResutCommentReply);
            context.Response.ContentType = "text/plain";
            context.Response.Write(data);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public IList<ScheduleCommentReplyEntity> GetCommentReplys(int commentId)
        {
            var scheduleCommentReplyMsg = new ScheduleCommentReplyMessage()
            {
                ReplyCommentId = commentId
            };
            return scheduleAdaptor.GetCommentReplysByCommentId(scheduleCommentReplyMsg);
        }
    }
}